package com.bbx.taxi.client.widget.textView;

import com.bbx.taxi.client.R;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

public class MyTextView extends View implements Runnable {
	private float x;// x坐标
	private float y;// y坐标
	private float step;// 移动步长
	private float contentWidth;// 文字宽度
	private Paint paint;
	private String wenzi;
	private int color;
	private int sudu;
	private int width, height;
	private TypedArray shuxing;
    private int cishu=0;
	public MyTextView(Context context, AttributeSet attrs) {
		super(context, attrs);

		shuxing = context.obtainStyledAttributes(attrs, R.styleable.CusView);
		color = shuxing.getColor(R.styleable.CusView_yanse, 0x000000);// 获取颜色，默认黑色
		sudu = shuxing.getInt(R.styleable.CusView_sudu, 100);// 获取速度，默认0.1秒
		wenzi = shuxing.getString(R.styleable.CusView_text);// 获取文字
		step = shuxing.getInt(R.styleable.CusView_step, 1);// 获取移动大小	
		// 画笔参数设置
		paint = new Paint();
		paint.setColor(Color.RED);
//		paint.setTextSize(25f);
		this.contentWidth = paint.measureText(wenzi); // 获取文字长度
		startMove();

	}
	//用于动态设置文字内容
   public void setText(String text){
	   wenzi=text;
   }
   public void setTextColor(int color){
	   paint.setColor(color);
   }
	// 启动线程
	public void startMove() {
		Thread thread = new Thread(this);
		thread.start();
	}

	@Override
	public void run() {
		try {
			while (true) {
				// 1.刷新
				postInvalidate();
				// 2.睡眠
				Thread.sleep(sudu);
				// 3.移動
				move();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);		
		
	}
	@Override
	protected void onDraw(Canvas canvas) {
		if(cishu==0){
			width = getWidth();
			height = getHeight();
			x = shuxing.getInt(R.styleable.CusView_x,width);// 获取x坐标
			y = shuxing.getInt(R.styleable.CusView_y, height / 2);// 获取y坐标
			cishu++;//用来控制不会调用多次
			}
		

		// 背景色
		canvas.drawColor(Color.TRANSPARENT);
		// 绘制文字
  
		canvas.drawText(wenzi, x, y, paint);
	}

	public void move() {
		
		x -= step;
		if (x < -contentWidth)// 移出屏幕后,从右侧进入
			x = 2 * width;// 这样才不会频繁的一直移动
	}
}
